package com.ycxy.school.express.service.impl;

import com.ycxy.school.express.ex.ServiceException;
import com.ycxy.school.express.mapper.FeedbackMapper;
import com.ycxy.school.express.pojo.dto.FeedbackAddNewDTO;
import com.ycxy.school.express.pojo.dto.FeedbackUpdateDTO;
import com.ycxy.school.express.pojo.entity.Feedback;
import com.ycxy.school.express.pojo.entity.User;
import com.ycxy.school.express.pojo.vo.AddressListItemVO;
import com.ycxy.school.express.pojo.vo.FeedbackListItemVO;
import com.ycxy.school.express.security.LoginPrincipal;
import com.ycxy.school.express.service.IFeedbackService;
import com.ycxy.school.express.web.ServiceCode;
import com.ycxy.school.express.web.enums.FeedbackStatusEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @Author jayLuo
 * @Date 2023/1/7 11:18
 * @PackageName:com.ycxy.school.express.service.impl
 * @ClassName: FeedbackServiceImpl
 * @Description: TODO
 * @Version 1.0
 */
@Service
@Slf4j
public class FeedbackServiceImpl implements IFeedbackService {

    @Autowired
    private FeedbackMapper feedbackMapper;

    @Override
    public void addNew(FeedbackAddNewDTO feedbackAddNewDTO) {
        log.debug("开始处理【添加用户反馈】的业务，参数：{}", feedbackAddNewDTO);
        //创建Feedback对象
        Feedback feedback = new Feedback();
        LocalDateTime now = LocalDateTime.now();
        BeanUtils.copyProperties(feedbackAddNewDTO,feedback);
        feedback.setUserId(getUserId());
        feedback.setStatus(FeedbackStatusEnum.WAIT.getStatus());
        feedback.setCreateData(now);
        // 调用FeedbackMapper的int insert(Feedback feedback)执行插入，并获取返回的行数
        int rows = feedbackMapper.insert(feedback);
        // 判断返回的行数是否不为1
        if (rows != 1) {
            // 是：抛出异常（ERR_DELETE：服务器忙）
            String message = "插入反馈数据失败，服务器忙，请稍后再尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }
    }

    @Override
    public void handleFeedback(Long id,FeedbackUpdateDTO feedbackUpdateDTO) {
        log.debug("开始处理【处理用户反馈】的业务，参数：{}", feedbackUpdateDTO);
        //创建Feedback对象
        Feedback feedback = new Feedback();
        LocalDateTime now = LocalDateTime.now();
        BeanUtils.copyProperties(feedbackUpdateDTO,feedback);
        feedback.setId(id);
        feedback.setStaffId(getUserId());
        feedback.setStatus(FeedbackStatusEnum.COMPLETE.getStatus());
        feedback.setModifiedData(now);
        // 调用FeedbackMapper的int updateById(Feedback feedback)执行修改，并获取返回的行数
        int rows = feedbackMapper.updateById(feedback);
        // 判断返回的行数是否不为1
        if (rows != 1) {
            // 是：抛出异常（ERR_DELETE：服务器忙）
            String message = "处理反馈失败，服务器忙，请稍后再尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE, message);
        }
    }

    @Override
    public void setProcess(Long id) {
        //创建Feedback对象
        Feedback feedback = new Feedback();
        LocalDateTime now = LocalDateTime.now();
        feedback.setId(id);
        feedback.setStatus(FeedbackStatusEnum.PROCESS.getStatus());
        feedback.setModifiedData(now);
        // 调用FeedbackMapper的int updateById(Feedback feedback)执行修改，并获取返回的行数
        int rows = feedbackMapper.updateById(feedback);
        // 判断返回的行数是否不为1
        if (rows != 1) {
            // 是：抛出异常（ERR_DELETE：服务器忙）
            String message = "将反馈标记为处理中失败，服务器忙，请稍后再尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE, message);
        }
    }

    @Override
    public void delete(Long id) {
        log.debug("开始处理【删除用户反馈】的业务，参数：{}", id);
        // 调用FeedbackMapper的int delete(Long id)执行删除，并获取返回的行数
        int rows = feedbackMapper.delete(id);
        // 判断返回的行数是否不为1
        if (rows != 1) {
            // 是：抛出异常（ERR_DELETE：服务器忙）
            String message = "删除用户反馈数据失败，服务器忙，请稍后再尝试！";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_DELETE, message);
        }
    }

    @Override
    public List<FeedbackListItemVO> list() {
        log.debug("开始处理【查询用户反馈列表】的业务，无参数");
        List<FeedbackListItemVO> list = feedbackMapper.list();
        return list;
    }

    @Override
    public List<FeedbackListItemVO> listByUserId() {
        log.debug("开始处理【根据用户id查询用户反馈列表】的业务");
        List<FeedbackListItemVO> list = feedbackMapper.listByUserId(getUserId());
        return list;
    }

    @Override
    public int countByWait() {
        log.debug("开始处理【统计等待处理的反馈数量】的业务");
        int rows = feedbackMapper.countByStatus(FeedbackStatusEnum.WAIT.getStatus());
        return rows;
    }

    @Override
    public int countByProcess() {
        log.debug("开始处理【统计处理中的反馈数量】的业务");
        int rows = feedbackMapper.countByStatus(FeedbackStatusEnum.PROCESS.getStatus());
        return rows;
    }

    @Override
    public int countByComplete() {
        log.debug("开始处理【统计处理完成的反馈数量】的业务");
        int rows = feedbackMapper.countByStatus(FeedbackStatusEnum.COMPLETE.getStatus());
        return rows;
    }

    public LoginPrincipal getUserInfo(){
        // 编写获取SpringSecurity上下文的代码
        LoginPrincipal principal = (LoginPrincipal)
                SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        // 为了逻辑严谨,判断一下SpringSecurity上下文中信息是不是null
        if(principal == null){
            throw new ServiceException(
                    ServiceCode.ERR_UNAUTHORIZED,"您没有登录!");
        }
        return principal;
    }

    // 业务逻辑层需求中,实际上只需要用户的id
    // 我们可以再编写一个方法,从用户对象中获取id
    public Long getUserId(){
        return getUserInfo().getId();
    }
}
